package com.cyw.controller;

import com.google.common.util.concurrent.ThreadFactoryBuilder;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.*;

/**
 * @Author: Chenyw
 * @Date: 2022/09/20/19:25
 */
@RestController
public class ThreadController {
    /**
     * 模拟多线程展示页面
     */


    public static void main(String[] args) throws InterruptedException, ExecutionException {
        // 使用 ThreadFactoryBuilder 创建自定义线程名称的 ThreadFactory
        ThreadFactory namedThreadFactory = new ThreadFactoryBuilder()
                .setNameFormat("pool-%d").build();

        long start = System.currentTimeMillis();
        /**
         * 多线程操作一下
         */

        ThreadPoolExecutor threadPool1 = new ThreadPoolExecutor(
                5,
                10,
                100,
                TimeUnit.SECONDS,
                new LinkedBlockingQueue<>(10),
                namedThreadFactory,
                new ThreadPoolExecutor.AbortPolicy());

        Future<String> task1 = threadPool1.submit(ThreadController::task1);
        Future<String> task2 = threadPool1.submit(ThreadController::task2);
        Future<String> task3 = threadPool1.submit(ThreadController::task3);

        System.out.println(task1.get());
        System.out.println(task2.get());
        System.out.println(task3.get());
        System.out.println((System.currentTimeMillis()-start)+"ms");

        // 优雅关闭线程池
        threadPool1.shutdown();
        threadPool1.awaitTermination(1000L, TimeUnit.SECONDS);
        // 任务执行完毕后打印"Done"
        System.out.println("Done");
    }

    private static String task1() throws InterruptedException {
        TimeUnit.SECONDS.sleep(1);
        return Thread.currentThread().getName()+"task1";
    }
    private static String task2() throws InterruptedException {
        TimeUnit.SECONDS.sleep(1);
        return Thread.currentThread().getName()+"task2";
    }
    private static String task3() throws InterruptedException {
        TimeUnit.SECONDS.sleep(1);
        return Thread.currentThread().getName()+"task3";
    }
}
